﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using PMS.Core.Utils;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using Pomelo.EntityFrameworkCore.MySql.Storage;
using System;

namespace PMS.Data.DbUtils
{
    /// <summary>
    /// Represents extensions of DbContextOptionsBuilder
    /// </summary>
    public static class DbContextOptionsBuilderExtensions
    {
        /// <summary>
        /// SQL Server specific extension method for Microsoft.EntityFrameworkCore.DbContextOptionsBuilder
        /// DavidLee 2019/12/20 更改以支持MySql
        /// </summary>
        /// <param name="optionsBuilder">Database context options builder</param>
        /// <param name="services">Collection of service descriptors</param>
        public static void UseDatabaseWithLazyLoading(this DbContextOptionsBuilder optionsBuilder, IServiceCollection services)
        {
            var dataSettings = DataSettingsManager.LoadSettings();
            if (!dataSettings?.IsValid ?? true)
                return;

            var dbContextOptionsBuilder = optionsBuilder.UseLazyLoadingProxies(false);

            switch (dataSettings.DataProvider)
            {
                case DataProviderType.SqlServer:
                    //dbContextOptionsBuilder.UseSqlServer(dataSettings.DataConnectionString);
                    //services.AddEntityFrameworkSqlServer();
                    throw new PMSException("SQL Server Not Supported yet!");
                case DataProviderType.MySql:
                    dbContextOptionsBuilder.UseMySql(dataSettings.ConnectionString,
                        mySqlOptions =>
                        {
                            mySqlOptions.ServerVersion(new ServerVersion(new Version(8, 0, 18), ServerType.MySql))
                                .CharSetBehavior(CharSetBehavior.AppendToAllColumns)
                                .CharSet(CharSet.Utf8Mb4);
                        });
                    services.AddEntityFrameworkMySql();
                    break;
                default:
                    throw new PMSException("Unknown database supporting");
            }
        }
    }
}
